package biznussoft.metercor.fragments;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import biznussoft.metercor.HomeActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.listeners.ActivityDetailListener;
import biznussoft.metercor.listeners.DialogListener;
import biznussoft.metercor.model.ActivityModel;
import biznussoft.metercor.model.Bean_Class;
import biznussoft.metercor.model.NewInventoryModel;
import biznussoft.metercor.utils.Base64;
import biznussoft.metercor.utils.Session;

import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;
public class ActivityDetailFragment extends BaseFragment implements OnClickListener   {
	private ActivityDetailListener listener;
	private static final int RESULT_CAMERA = 1;
	private TextView tvStep,tvActivityname,tvstatus,tvstarttime,tvendtime,tvServiceOrder,
	tvPriority,tvDuration,tvDate,tvTime,tvMaterial,tvExpenses,tvEditedServiceOrder;
	private EditText etStep,etActivityname,etstarttime,etendtime;
	private Spinner spStatus,spPriority;
	private CheckBox cbBillable,cbEditBillable;
	private RestClient client;
	private ActivityModel mobel;
	private DialogListener dialoglistener;
	private LinearLayout viewMode,editMode;
	private ImageView signatureCapture,imageCapture,sign,image;
	private String mFileName,mImagePath,serviceOrder;
	private String strSignature,strImage,step,starttime,endTime,activityName;
	private Button save;
	private LinearLayout activityLayout;
	String strId;
	public static ArrayList<NewInventoryModel> itemIdDetails;
	private MenuItem edit,logout;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.activity_detail_fragment, null);
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		edit = menu.add("Edit");                 
		MenuItemCompat.setShowAsAction(edit,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		edit.setIcon(R.drawable.edit); 
		logout = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(logout,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		logout.setIcon(R.drawable.logout); 
		super.onCreateOptionsMenu(menu, inflater);                              
	}


	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}
		if(item.getTitle().equals("Edit")){
			edit.setVisible(false);
			viewMode.setVisibility(View.GONE);
			editMode.setVisibility(View.VISIBLE);
			tvEditedServiceOrder.setText(serviceOrder);
			etStep.setText(step);
			etendtime.setText(endTime);
			etActivityname.setText(activityName);
			etstarttime.setText(starttime);
		}
		return super.onOptionsItemSelected(item);

	}


	@Override
	public void onAttach(Activity activity) {                        
		// TODO Auto-generated method stub
		super.onAttach(activity);
		listener = (ActivityDetailListener) getActivity();
		dialoglistener = (DialogListener) getActivity();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		client =  HomeActivity.mActivity.client;

		activityLayout = (LinearLayout) getView().findViewById(R.id.activityLayout);
		spStatus = (Spinner)getView().findViewById(R.id.spStatus);
		spPriority = (Spinner)getView().findViewById(R.id.spPriority);

		etStep = (EditText) getView().findViewById(R.id.etStep);
		etActivityname = (EditText) getView().findViewById(R.id.etActivityname);
		etstarttime = (EditText) getView().findViewById(R.id.etStartTime);
		etendtime = (EditText) getView().findViewById(R.id.etEndTime);
		etstarttime.setOnClickListener(this);
		etendtime.setOnClickListener(this);
		signatureCapture = (ImageView) getView().findViewById(R.id.signImage);
		signatureCapture.setOnClickListener(this);
		sign = (ImageView) getView().findViewById(R.id.signature);
		imageCapture = (ImageView) getView().findViewById(R.id.captureImage);
		imageCapture.setOnClickListener(this);
		image = (ImageView) getView().findViewById(R.id.picture);
		save = (Button) getView().findViewById(R.id.save);
		save.setOnClickListener(this);
		viewMode = (LinearLayout) getView().findViewById(R.id.lllayoutActivityViewMode);
		editMode = (LinearLayout) getView().findViewById(R.id.lllayoutActivityEditMode);

		tvStep = (TextView) getView().findViewById(R.id.tvStep);
		tvendtime = (TextView) getView().findViewById(R.id.tvEndTime);
		tvActivityname = (TextView) getView().findViewById(R.id.tvActivityname);
		tvstatus = (TextView) getView().findViewById(R.id.tvStatus);
		tvstarttime = (TextView) getView().findViewById(R.id.tvStartTime);
		cbBillable = (CheckBox) getView().findViewById(R.id.tvBillable);
		cbEditBillable  = (CheckBox) getView().findViewById(R.id.cbEditBillable);
		tvServiceOrder = (TextView) getView().findViewById(R.id.tvServiceOrder);
		tvEditedServiceOrder = (TextView) getView().findViewById(R.id.tvEditServiceOrder);
		tvPriority = (TextView) getView().findViewById(R.id.tvPriority);
		tvDuration = (TextView) getView().findViewById(R.id.tvDuration);
		tvDate = (TextView) getView().findViewById(R.id.tvDate);

		tvTime = (TextView) getView().findViewById(R.id.time);
		tvMaterial = (TextView) getView().findViewById(R.id.material);
		tvExpenses = (TextView) getView().findViewById(R.id.expenses);

		tvTime.setOnClickListener(this);
		tvMaterial.setOnClickListener(this);
		tvExpenses.setOnClickListener(this);

		mFileName = "image"+".jpg";
		mImagePath = Environment.getExternalStoragePublicDirectory("download")+"/canvas/";
	}


	public void getSignature(String signature){
		try{
			strSignature = signature;
			byte[] decodedString = Base64.decode(signature);
			Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
			sign.setImageBitmap(decodedByte);
		}catch (Exception e) {
		}

	}

	public void setStartDate(String date){

		etstarttime.setText(date);
	}
	public void setEndDate(String date){

		etendtime.setText(date);

	}


	public void  getDetailsFromMyActiviites(int position){




		try{
			mobel = MyActivitiesMasterFragment.myActivitiesserviceOrderSubList.get(position);
			step = mobel.getStep();
			tvStep.setText(step);
			strId = mobel.getId();
			Session.sActivityId  = strId;
			endTime = mobel.getEndTime();                
			tvendtime.setText(endTime);
			activityName ="";
			tvActivityname.setText(activityName);
			tvstatus.setText(mobel.getStatus());
			starttime = mobel.getStartTime();
			tvstarttime.setText(starttime);  
			
			Session.sServiceOrderId = mobel.getSiteID();             
			
			if(mobel.getTechicianId().equalsIgnoreCase(Session.sID.substring(0, Session.sID.length()-3))){
				
				activityLayout.setVisibility(View.VISIBLE);              
			}
			
			//tvServiceOrder.setText(serviceOrder);
			//						tvPriority.setText(activities.getString(""));
			/*tvDuration.setText(activities.getString("FConnect__Duration__c"));*/
			//						tvDate.setText(activities.getString(""));
			
			retriveItems();

		} catch (Exception e) {
		}
	}




	public void getWarehouseDetails(int Position,String category){   

		serviceOrder = category;
		mobel = ServiceOrderDetailsFragment.list.get(Position);
		Session.sFconnectActivity =mobel.getActivityName();

		step = mobel.getStep();
		tvStep.setText(step);
		endTime = mobel.getEndTime();
		tvendtime.setText(endTime);
		activityName = mobel.getActivityNameNew();
		tvActivityname.setText(activityName);

		tvstatus.setText(mobel.getStatus());
		starttime = mobel.getStartTime();
		tvstarttime.setText(starttime);
		if(mobel.isBillable()){
			cbBillable.setChecked(true);
		}else{
			cbBillable.setChecked(false);
		}
		tvServiceOrder.setText(serviceOrder);
		tvPriority.setText(mobel.getPriority());
		tvDuration.setText(mobel.getDuration());
		tvDate.setText(mobel.getDate());
		strId = mobel.getId();
		
		activityLayout.setVisibility(View.VISIBLE);
		
		retriveItems();

	}

	public void retriveItems(){

		try{

			String accounts = "SELECT Name,Id,FConnect__Lot_ID__c,FConnect__Serial_ID__c FROM FConnect__Inventory__c where FConnect__Site__c="+"'"+Session.sServiceOrderId+"'";
			
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {


						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						itemIdDetails = new ArrayList<NewInventoryModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								NewInventoryModel bean = _gson.fromJson(jsonArray.getString(i), NewInventoryModel.class);
								itemIdDetails.add(bean);
							}
						}     


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);

				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.time:
			listener.getCategory("time",strId);
			break;
		case R.id.material:
			listener.getCategory("material",strId);
			break;
		case R.id.expenses:
			listener.getCategory("expenses",strId);
			break;

		case R.id.save:
			updateAccount(strId);
			break;
		case R.id.signImage:                
			dialoglistener.nextDialog("sign");
			break;
		case R.id.etStartTime:

			Session.sStartTime = true;
			Session.sEndTime = false;
			Session.sActivity = true;
			Session.sTime = false;
			Session.sExpense = false;
			Session.sNewTime = false;
			Session.sNewExpenses = false;
			dialoglistener.nextDialog("date");
			break;
		case R.id.etEndTime:

			Session.sStartTime = false;
			Session.sEndTime = true;
			Session.sActivity = true;
			Session.sTime = false;
			Session.sExpense = false;
			Session.sNewTime = false;
			Session.sNewExpenses = false;
			dialoglistener.nextDialog("date");
			break;
		case R.id.captureImage:
			File file = checkFileExistence(mImagePath, mFileName);
			init_Camera(file);
			break;
		default:
			break;
		}
	}

	
	public void updateAccount(String id){               
		String objectType = "FConnect__Activitie__c";
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("Name",etStep.getText().toString());              
	/*	fields.put("FConnect__Planned_End_Date_Time__c",etendtime.getText().toString());
		fields.put("FConnect__Planned_Start_DateTime__c",etstarttime.getText().toString());*/
		fields.put("FConnect__Status__c", spStatus.getSelectedItem().toString());
		fields.put("FConnect__Priority__c",spPriority.getSelectedItem().toString());
		//fields.put("FConnect__Billable__c",Boolean.toString(cbEditBillable.isChecked()));
//		fields.put("FConnect__Activity__c",etActivityname.getText().toString());
		fields.put("sign__c","<img src="+"\"data:image/png;base64,"+strSignature+"\"/>");                                                                                                                                            
		fields.put("Picture__c","<img src="+"\"data:image/png;base64,"+strImage+"\"/>" );   

		try {

			RestRequest restRequest = RestRequest.getRequestForUpdate(Bean_Class.api_Version,objectType,id,fields);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {
						Log.i("TPT","result is   :"+result);    
						finish();            
					}                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}

				//@Override
				public void onError(Exception exception) {

					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());

		}

	}

	public void finish(){                                                                                                                            
		getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit();
	}

	public static File checkFileExistence(String path, String fileName) {
		if (!new File(path).exists()) {
			new File(path).mkdirs();
		}
		File file = new File(path, fileName);
		return file;
	}                

	public void init_Camera(File file) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
		startActivityForResult(intent,RESULT_CAMERA);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			try {
				UpdateUIWithImages(mFileName);
			} catch (Exception e) {
				Log.i("Today","Display Image"+e.getMessage());
			}
		}
	}

	private void UpdateUIWithImages(String fileName) throws Exception {

		File file = new File(mImagePath+"/"+fileName);
		Bitmap bitmap  = getFileFromStorage(file);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
		byte[] imagebyte = stream.toByteArray();             
		/*String img_str = Base64.encodeToString(imagebyte, Base64.DEFAULT);     
    	byte[] decodedString = Base64.decode(img_str, Base64.DEFAULT);
    	Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
    	image.setImageBitmap(decodedByte);  */        
		strImage = Base64.encodeBytes(imagebyte);     
		byte[] decodedString = Base64.decode(strImage);
		Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
		image.setImageBitmap(decodedByte);  
	}

	private Bitmap getFileFromStorage(File file) throws Exception {
		try {
			// decode image size
			Bitmap retBmp = null;
			System.gc();
			int scale = 1;
			if (file.length() > 400000) {
				scale = 4;
			} else if (file.length() > 100000 && file.length() < 400000) {
				scale = 2;
			}
			// decode with inSampleSize
			if (file.exists()) {
				BitmapFactory.Options bitmapFactoryObject = new BitmapFactory.Options();
				bitmapFactoryObject.inSampleSize = scale;
				retBmp = BitmapFactory.decodeFile(file.getPath(), bitmapFactoryObject);
			}

			return rotateImage(retBmp, file.getPath());
		} catch (Exception t) {
			t.printStackTrace();
			// CustomLogHandler.printErrorlog(t);
			throw new Exception(
					"Today"
							+ " Error in getFileFromStorage(File p_file) of ImageLoader",
							t);
		}
	}
	private Bitmap rotateImage(Bitmap decodedbitMap, String path) throws Exception {
		try {
			ExifInterface exif = new ExifInterface(path);
			String orientString = exif
					.getAttribute(ExifInterface.TAG_ORIENTATION);
			int orientation = orientString != null ? Integer
					.parseInt(orientString) : ExifInterface.ORIENTATION_NORMAL;
					int rotationAngle = 0;
					if (orientation == ExifInterface.ORIENTATION_ROTATE_90)
						rotationAngle = 90;
					if (orientation == ExifInterface.ORIENTATION_ROTATE_180)
						rotationAngle = 180;
					if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
						rotationAngle = 270;

					Matrix matrix = new Matrix();
					matrix.setRotate(rotationAngle);
					Bitmap rotatedBitmap = Bitmap.createBitmap(decodedbitMap, 0, 0,
							decodedbitMap.getWidth(), decodedbitMap.getHeight(), matrix, true);
					//
					FileOutputStream fileOutputStream = new FileOutputStream(path);
					rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 50,
							fileOutputStream);

					return rotatedBitmap;

		}

		catch (Throwable t) {
			// CustomLogHandler.printErrorlog(t);
			throw new Exception("Today" + " Error in rotateImage:", t);
		}

	}

}
